﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using CoolCode.Reflection;

namespace CoolCode.Data.Xml
{
    class XmlConvert
    {
        public static XElement Entity2Xml<T>(T TEntity)
        {
            var className = BLReflection.GetClassName<T>();
            var dict = BLReflection.ToDictionary<T>(TEntity);
            XElement xe = new XElement(className);
            foreach (var d in dict)
                xe.Add(new XElement(d.Key, SerializeObject(d.Value)));
            return xe;
        }

        public static T Xml2Entity<T>(XElement x)
        {
            return (T)Xml2Entity(x, typeof(T)) ;
        }

        public static object Xml2Entity(XElement x, Type targetType)
        {
            object t = Activator.CreateInstance(targetType);
            var ps = BLReflection.GetProperties(targetType);
            foreach (var p in ps)
            {
                Type type = p.PropertyType;
                object value = null;
                if (type.Name == typeof(string).Name)
                    value = x.Element(p.Name).Value;
                else
                    value = DeserializeObject(x.Element(p.Name).Value, type);
                p.SetValue(t, value, null);
            }
            return t;
        }

        public static string SerializeObject(object obj)
        {
            return Converter<string>.Default.Serialize(obj);
        }

        public static object DeserializeObject(string value, Type type)
        {
            return Converter<string>.Default.Deserialize(value, type);
        }

    }
}
